import React, { Component, PureComponent } from 'react';
import {
	Text,
	View,
	Image,
	StyleSheet,
	FlatList,
	TextInput,
	RefreshControl,
	TouchableOpacity,
	DeviceEventEmitter,
	AsyncStorage,
} from 'react-native';
import { Actions } from 'react-native-router-flux';
import ScrollableTabView, { ScrollableTabBar } from 'react-native-scrollable-tab-view';

import ActionCodes from '../../config/ActionCodes';
import { postFetch, getFetch } from '../../utils/network/request/HttpExtension.js';
import DeviceUtils from '../../utils/DeviceUtils.js'

export default class NewsListTab extends Component {
    dataContainer = [];
    currentPage = 0;
    pageSize = 10

	constructor(props) {
		super(props);
		this.state = {
			sourceData: [],
			refreshing: false,
			selected: (new Map(): Map<String, boolean>),
			indexText: '',
        };
	}

	componentDidMount() {
		// // 初始化数据
		// for (let i = 0; i < 20; i++) {
		//     let obj = {
		//         id: i,
		//         title: i + '只柯基'
		//     };
		//     this.dataContainer.push(obj);
		// }

		// this.setState({
		//     sourceData: this.dataContainer
		// });
        // if(this.state.mounted != true ){
        //     alert('dd')
            this.GetArticleForMobileIndexByUserIdAndCategoryId(this.props.categoryID)
        // }
        this.setState({ mounted: true })
    }

    shouldComponentUpdate(nextProps, nextState) {
       
        if (nextState.sourceData == this.state.sourceData){
            return false
        }
        return true
    }
    
    GetArticleForMobileIndexByUserIdAndCategoryId(categoryId,currentPage = 0, pageSize = 10, paramTitle = '') {
		let param = {
			SearchType: '0',
			CATEGORY_ID: categoryId,
			TITLE: paramTitle,
			PageIndex: currentPage,
			PageSize: pageSize,
			SortBy: 'AUDIT_DATE DESC',
        };

		postFetch(ActionCodes.newsList, param)
			.then(res => {
                this.dataContainer = this.dataContainer.concat(res.List);
                // alert(JSON.stringify(res.List))
				this.setState({
                    sourceData: this.dataContainer
				})
				this.currentPage++;
			})
			.catch(err => {
				alert(err);
				
			});
    }

	/**
	 * 此函数用于为给定的item生成一个不重复的Key。
	 * Key的作用是使React能够区分同类元素的不同个体，以便在刷新时能够确定其变化的位置，减少重新渲染的开销。
	 * 若不指定此函数，则默认抽取item.key作为key值。若item.key也不存在，则使用数组下标
	 *
	 * @param item
	 * @param index
	 * @private
	 */
	_keyExtractor = (item, index) => index.toString();

	/**
	 * 使用箭头函数防止不必要的re-render；
	 * 如果使用bind方式来绑定onPressItem，每次都会生成一个新的函数，导致props在===比较时返回false，
	 * 从而触发自身的一次不必要的重新render，也就是FlatListItem组件每次都会重新渲染。
	 *
	 * @param id
	 * @private
	 */
	_onPressItem = id => {
		this.setState(state => {
			const selected = new Map(state.selected);
			selected.set(id, !selected.get(id));
			return { selected };
		});
	};

	// 跳转到指定位置
	_doActionToItem = () => {
		// viewPosition: 指定选定行显示的位置，0代表top，0.5代表middle，1代表bottom
		this.flatList.scrollToIndex({ viewPosition: 0, index: this.state.indexText });
	};

	// 跳转到内容最底端
	_doActionToBottom = () => {
		this.flatList.scrollToEnd();
	};

	// Header布局
	_renderHeader = () => (
		<View style={{ flexDirection: 'row' }}>
			<TextInput
				style={{ height: 50, flex: 1 }}
				placeholder="请输入行号"
				onChangeText={text => {
					this.setState({ indexText: text });
				}}
			/>
			<TouchableOpacity
				onPress={this._doActionToItem}
				style={{
					height: 50,
					width: 90,
					backgroundColor: 'green',
					justifyContent: 'center',
					alignItems: 'center',
				}}
			>
				<Text style={{ color: '#fff' }}>跳转到指定行</Text>
			</TouchableOpacity>
			<TouchableOpacity
				onPress={this._doActionToBottom}
				style={{
					height: 50,
					width: 90,
					backgroundColor: 'red',
					justifyContent: 'center',
					alignItems: 'center',
				}}
			>
				<Text style={{ color: '#fff' }}>跳转到底部</Text>
			</TouchableOpacity>
		</View>
	);

	// Footer布局
	_renderFooter = () => (
		<View>
			<Text>Footer</Text>
		</View>
	);

	// 自定义分割线
	_renderItemSeparatorComponent = ({ highlighted }) => <View style={{ height: 0.5, backgroundColor: '#dfdfdf' }} />;

	// 空布局
	_renderEmptyView = () => (
		<View style={{ flex:1, alignSelf:'center', }}>
			<Text style={{ fontSize: 20,color: 'gray'}}>数据加载中...</Text>
		</View>
	);

	// 下拉刷新
	_renderRefresh = () => {
		this.setState({ refreshing: true }); //开始刷新
		//这里模拟请求网络，拿到数据，3s后停止刷新
		setTimeout(() => {
			this.setState({ refreshing: false });
		}, 3000);
	};

	// 上拉加载更多
	_onEndReached = () => {
		if(this.currentPage > 0)
        // if(!this.onEndReachedCalledDuringMomentum){
		    this.GetArticleForMobileIndexByUserIdAndCategoryId(this.props.categoryID,this.currentPage)
        //     this.onEndReachedCalledDuringMomentum = true;
        // }
        
	};

	_renderItem = ({ item }) => {
		return (
			<TodoCell
				id={item.ID}
				onPressItem={this._onPressItem}
				selected={!!this.state.selected.get(item.id)}
				item={item}
			/>
		);
	};

	render() {
		return (
			<FlatList
				ref={ref => (this.flatList = ref)}
				data={this.state.sourceData}
				extraData={this.state.selected}
				keyExtractor={this._keyExtractor}
				renderItem={this._renderItem}
				// 决定当距离内容最底部还有多远时触发onEndReached回调；数值范围0~1，例如：0.5表示可见布局的最底端距离content最底端等于可见布局一半高度的时候调用该回调
				onEndReachedThreshold={0.1}
				// 当列表被滚动到距离内容最底部不足onEndReacchedThreshold设置的距离时调用
                onEndReached={ this._onEndReached }
                onMomentumScrollBegin={() => { this.onEndReachedCalledDuringMomentum = false; }}
				// ListHeaderComponent={ this._renderHeader }
				// ListFooterComponent={ this._renderFooter }
				ItemSeparatorComponent={this._renderItemSeparatorComponent}
				ListEmptyComponent={this._renderEmptyView}
				refreshing={this.state.refreshing}
				onRefresh={this._renderRefresh}
				// 是一个可选的优化，用于避免动态测量内容；+50是加上Header的高度
				getItemLayout={(data, index) => ({ length: 40, offset: (40 + 1) * index + 50, index })}
			/>
		);
	}
}

class TodoCell extends PureComponent {
	_onPress = () => {
		Actions.todo({news: this.props.item});
	};

	render() {
		return (
			<TouchableOpacity onPress={this._onPress}>
				<View style={styles.cell_container}>
					<Text style={styles.title}>{this.props.item.TITLE}</Text>
					{/* <Text style={styles.description}>{this.props.title}</Text> */}
					<View style={{ flexDirection: 'row', justifyContent: 'space-between' }}>
						<View style={{ flexDirection: 'row', alignItems: 'center' }}>
							<Text style={styles.description}>作者:{this.props.item.USER_NAME}</Text>
						</View>

						<View style={{ flexDirection: 'row', alignItems: 'center' }}>
							<Text style={styles.description}>审批日期:{ (new Date(this.props.item.AUDIT_DATE)).toLocaleString() }</Text>
						</View>
						<Image
							style={{ width: 22, height: 22 }}
							source={require('../../../res/image/TabBar_yewubanli_current.png')}
						/>
					</View>
				</View>
			</TouchableOpacity>
		);
	}
}

const styles = StyleSheet.create({
	container: {
		flex: 1,
	},
	title: {
		fontSize: 16,
		marginBottom: 2,
	},
	description: {
		fontSize: 14,
		marginBottom: 2,
		color: '#757575',
		borderRadius: 2,
		marginTop:5
	},
	cell_container: {
		backgroundColor: 'white',
		padding: 10,
		marginLeft: 5,
		marginRight: 5,
		marginVertical: 3,
		borderWidth: 0.5,
		borderColor: '#dddddd',
		shadowColor: 'gray',
		shadowOffset: { width: 0.5, height: 0.5 },
		shadowOpacity: 0.4,
		shadowRadius: 1,
		elevation: 2,
	},
});
